<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件委托</title>
  </head>
  <body>
    <ul id="myLinks">
      <li id="goSomewhere">Go somewhere</li>
      <li id="doSomething">Do something</li>
      <li id="sayHi">Say hi</li>
    </ul>
  </body>
  <script>
    // 方案一
    let item1 = document.getElementById('goSomewhere');
    let item2 = document.getElementById('doSomething');
    let item3 = document.getElementById('sayHi');
    item1.addEventListener('click', (event) => {
      location.href = 'http:// www.wrox.com';
    });
    item2.addEventListener('click', (event) => {
      document.title = "I changed the document's title";
    });
    item3.addEventListener('click', (event) => {
      console.log('hi');
    });
    //方案二 事件委托
    let list = document.getElementById('myLinks');
    list.addEventListener('click', (event) => {
      let target = event.target;
      switch (target.id) {
        case 'doSomething':
          document.title = "I changed the document's title";
          break;
        case 'goSomewhere':
          location.href = 'http:// www.wrox.com';
          break;
        case 'sayHi':
          console.log('hi');
          break;
      }
    });
    // 这里只给<ul id="myLinks">元素添加了一个 onclick 事件处理程序。因为所有列表项都是这个
    // 元素的后代，所以它们的事件会向上冒泡，最终都会由这个函数来处理。但事件目标是每个被点击的列
    // 表项，只要检查 event 对象的 id 属性就可以确定，然后再执行相应的操作即可。
  </script>
</html>
